package com.museum.controller.impl;

import com.alibaba.csp.sentinel.cluster.TokenService;
import com.alibaba.fastjson.JSONObject;
import com.museum.base.BaseApiService;
import com.museum.base.BaseResponse;
import com.museum.constants.Constants;
import com.museum.controller.api.UserAPI;


import com.museum.core.utils.GetIPV4;
import com.museum.core.utils.RedisUtil;
import com.museum.entity.DO.Permission;
import com.museum.entity.DO.Token;
import com.museum.entity.DO.User;
import com.museum.entity.DTO.RedisInfo.userInfo;
import com.museum.entity.DTO.permission.PermissionShow;
import com.museum.entity.DTO.user.*;
import com.museum.service.api.PermissionServiceAPI;
import com.museum.service.api.TokenServiceAPI;
import com.museum.service.api.UserServiceAPI;

import com.museum.token.GenerateToken;
import com.museum.transaction.RedisDataSourceTransaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * @Description:
 * @ClassName museum
 * @Author: 王瑞文
 * @Date: 2020/12/2 16:25
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseApiService<JSONObject> implements UserAPI {
    @Autowired
    private UserServiceAPI userServiceAPI;
    @Autowired
    private TokenServiceAPI tokenServiceAPI;
    @Autowired
    private RedisDataSourceTransaction transaction;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private GenerateToken generateToken;
    @Autowired
    private PermissionServiceAPI permissionServiceAPI;

    @Override
    public BaseResponse<JSONObject> userRegister(UserRegister userRegister) {
        return null;
    }

    @Override
    public BaseResponse<JSONObject> getMessage(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String value = redisUtil.getString(token);
        userInfo userInfo = JSONObject.parseObject(value, com.museum.entity.DTO.RedisInfo.userInfo.class);
        Integer userID = userInfo.getUserId();
        Integer areaNumber = userInfo.getAreaNumber();
        if (StringUtils.isEmpty(userID))
            return setResultError("登录身份已经过期请重新登陆");
        HashMap<String,Object> map = new HashMap<>();
        map.put("userId",userID); map.put("areaNumber",areaNumber);
        userAreaDTO user = userServiceAPI.selectById(map);
        JSONObject object = new JSONObject();
        object.put("userMessage", user);
        return setResultSuccess(object);
    }

    @Override
    public BaseResponse<JSONObject> logout(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        redisUtil.delKey(token);
        System.out.println("退出的时候的token="+token);
        int flag  = tokenServiceAPI.logout(token);
        if(flag>0){
            return setResultSuccess("成功退出");
        }else{
            return setResultError("退出失败！");
        }
    }

    @Override
    public BaseResponse<JSONObject> getMenu(HttpServletRequest request) {
        //从user中拿到 用户的地域id  根据地域的id来从area_permission中拿到权限 拿到list<String> permissions
        // 以及从user_role表中拿到角色 根据角色拿到id  -----List<String> ids
        String token = request.getHeader("Authorization");
        String value = redisUtil.getString(token);
        userInfo userInfo = JSONObject.parseObject(value, userInfo.class);
        Integer userID = userInfo.getUserId();
        Integer areaNumber = userInfo.getAreaNumber();
        List<Integer> areaPermission = userServiceAPI.getUserAreaPermission(areaNumber);
        List<Integer> userPermission = userServiceAPI.getUserPermission(userID);
        //去重
        List<Integer> permissions = userServiceAPI.endPermission(areaPermission,userPermission);
        List<Permission> permissionList = new ArrayList();
        for (int permissionId : permissions) {
            Permission permission = permissionServiceAPI.queryPermissionById(permissionId);
            if (permission != null)
                permissionList.add(permission);
        }
        //权限的集合 permissionList 将集合转换为树形结构
        List<PermissionShow> list = permissionServiceAPI.build(permissionList);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("menus",list);
        return setResultSuccess(jsonObject);
    }

    @Override
    public  synchronized BaseResponse<JSONObject> userLoginByUserName(HttpServletRequest request, UserLoginByName userLogin) {
        if(userLogin==null){
            return ParamError();
        }
        String userName = userLogin.getUsername();
        String userPassword = userLogin.getPassword();
        Integer status = userServiceAPI.getStatus(userName,userPassword);
        userInfo userInfo = userServiceAPI.userLoginByName(userName, userPassword);
        if (StringUtils.isEmpty(userInfo)) {
            return setResultError("用户名或密码错误,请检查");
        } else {
            if(status.equals(1)){
                return setResultError("该用户无法使用,请联系管理员");
            }
            return loginCommon(request, userInfo);
        }
    }

    private synchronized BaseResponse<JSONObject> loginCommon(HttpServletRequest request, userInfo userInfo) {
        TransactionStatus transactionStatus = null; //开启数据库和redis事务同步
        Token oldToken = tokenServiceAPI.isExit(userInfo.getUserId());
        transactionStatus = transaction.begin();
        if(oldToken!=null){
            //有活跃的信息 将活跃的信息设置为不活跃
            oldToken.setIsAvailability(1);
            if(tokenServiceAPI.updateById(oldToken)<=0){
                //跟新失败 事务回滚
                try{
                    transaction.rollback(transactionStatus);
                }catch(Exception e){
                    e.printStackTrace();
                }
                return setResultError("token更新失败,系统错误！");
            }
            //删除对象
            redisUtil.delKey(oldToken.getToken());
        }
        JSONObject jsonObject = new JSONObject();
		String info = jsonObject.toJSONString(userInfo);
        String token = generateToken.createToken(Constants.MEMBER_TOKEN_KEYPREFIX, info, Constants.TOKEN_MEMBER_TIME);
        Token newToken = new Token();
        newToken.setToken(token);
        newToken.setDeviceInfor(GetIPV4.webBrowserInfo(request));
        newToken.setIpv4(GetIPV4.getIPV4Address(request));
        newToken.setUserId(userInfo.getUserId());
        newToken.setIsAvailability(0);
        newToken.setLoginType("PC");
       // System.out.println("此时新的token"+newToken);
        if (tokenServiceAPI.insert(newToken) <= 0) {
            try {
                transaction.rollback(transactionStatus);
                return setResultError("同步故障");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //提交事务
        try {
            transaction.commit(transactionStatus);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject object = new JSONObject();
        object.put("userInfo", userInfo);
        object.put("token", token);
        return setResultSuccess(object);
    }

    @Override
    public synchronized BaseResponse<JSONObject> AddUser(HttpServletRequest request,UserAdd userAdd) {
        if (userAdd == null) {
            return ParamError();
        }
        return  userServiceAPI.userAdd(request,userAdd);
    }

    @Override
    public BaseResponse<JSONObject> deleteId(HttpServletRequest request, Integer userId) {
        return userServiceAPI.deleteUserById(request,userId);
    }

    @Override
    public BaseResponse<JSONObject> getAllUser(long current, long limit, UserQuery userQuery,HttpServletRequest request) {
        return  userServiceAPI.getAllUserByPage(current,limit,userQuery,request);
    }

    @Override
    public BaseResponse<JSONObject> updateUser(HttpServletRequest request, UserAdd user) {
        return userServiceAPI.updateUser(request,user);
    }
}
